<?php

/**
 * 后台用户相关model
 */
namespace backend\models;

use Yii;
use yii\db\ActiveRecord;
use yii\data\Pagination;
use yii\data\ArrayDataProvider;
use backend\models\Admin;
use backend\models\novel\Novel;

class Visitor extends ActiveRecord
{
    /**
     * 获取admin列表
     */
    public function getVisitorList( $params = array() )
    {
        $data = array(
            'list' => array(),
            'count' => 0,
        );
        $visit = self::find();
        $visit->select('*');
        if(isset($params['start']) && $params['start']){
            $visit->andWhere("last_login_time >= :st");
            $visit->addParams(array(":st"=>$params['start']));
        }
        if(isset($params['end']) && $params['end']){
            $visit->andWhere("last_login_time <= :et");
            $visit->addParams(array(":et"=>$params['end']));
        }
        $page = $params['page'];
        $offset = 0;
        $limit = $params['pageSize'];
        if($page > 0){
            $offset = ($page - 1) * $limit;
        }
        $count = $visit->count();
        $visit->orderBy('last_login_time desc');
        $visit->offset($offset)->limit($limit);
        $result = $visit->asArray()->all();
        if($result){
            //合作方、渠道
            $pids = array_column( $result , 'partner_id' );
            $cids = array_column( $result , 'channel_id' );
            $admin = new Admin();
            $param['ids'] = array_unique( array_merge_recursive( $pids , $cids ) );
            $admins = $admin->getAdminList( $param );
            $a_k_v = array_column( $admins['list'] , null , 'id' );
            unset($admins);
            //小说来源
            $novel_id = array_column( $result , 'novel_id' );
            $novel = new Novel();
            $novels = $novel->getNovelList( array( 'ids' => array_unique( $novel_id ) ) );
            $n_k_v = array_column( $novels['list'] , null , 'novel_id' );
            unset($novels);
            foreach($result as $k=>$v){
                $result[$k]['partner'] = isset($a_k_v[$v['partner_id']]) ? $a_k_v[$v['partner_id']]['username'] : '无';
                $result[$k]['channel'] = isset($a_k_v[$v['channel_id']]) ? $a_k_v[$v['channel_id']]['username'] : '无';
                $result[$k]['novel']   = isset($n_k_v[$v['novel_id']]) ? $n_k_v[$v['novel_id']]['novel_title'] : '无';
            }
        }
        $data['dataProvider'] = new ArrayDataProvider(array(
            'allModels'=> $result ? $result : array(),
//            'sort' => [
//                'attributes' => ['userId', 'createTime', 'sex', 'nickname','lastTime'],
//            ],
        ));
        $data['pagination'] = new Pagination(array(
            'defaultPageSize'   => $limit,
            'totalCount'        => $count ? $count : 0,
        ));
        return $data;
    }
}

